package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.tenant.TenantManager;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.one.group.admin.mapper.UserAccountMapper;
import com.one.group.model.dto.AddOwnerAccountNumberDto;
import com.one.group.model.dto.UserLoginDto;
import com.one.group.model.entity.UserAccount;
import com.one.group.service.UserAccountService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import java.util.UUID;
@DubboService
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {
    @Override
    public boolean addOwnerAccountNumber(AddOwnerAccountNumberDto addOwnerAccountNumberDto) {
        //构建信息
        UserAccount userAccount = new UserAccount();
        userAccount.setPhone(addOwnerAccountNumberDto.getPhone());
        userAccount.setRealName(addOwnerAccountNumberDto.getName());
        userAccount.setIdCard(addOwnerAccountNumberDto.getIdCard());
        userAccount.setEmail(addOwnerAccountNumberDto.getEmail());
        userAccount.setCellId(addOwnerAccountNumberDto.getCellId());
        //通过手机号后六位构建密码字段
        String password = addOwnerAccountNumberDto.getPhone().substring(5);
        //构建盐
        String salt = UUID.randomUUID().toString();
        userAccount.setSalt(salt);
        //密码加密
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String md5Password = md5.digestHex(password + salt);
        userAccount.setPassword(md5Password);
        //随机生成六位用户名字段
        String username = UUID.randomUUID().toString().substring(0, 6);
        userAccount.setUsername(username);
        userAccount.setStatus(0);
        userAccount.setGender(addOwnerAccountNumberDto.getGender());
        return getMapper().insert(userAccount, true) != 0;
    }

    @Override
    public UserAccount mySelectOneByQuery(UserLoginDto userloginDto) {
        //1.根据用户名查询用户信息
        QueryWrapper lambdaQueryWrapper = QueryWrapper.create().from(UserAccount.class);
        lambdaQueryWrapper.eq(UserAccount::getPhone, userloginDto.getPhone());
        //配置忽略多租户
        TenantManager.ignoreTenantCondition();
        return getMapper().selectOneByQuery(lambdaQueryWrapper);
    }
}
